package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws SQLException, IntrospectionException, NoSuchFieldException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
        //将要去完成对simpleExecutor里的 query方法 的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        //根据statementId获取到对应的mappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        //调用simpleExecutor里的query方法
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        //将list里的结果进行类型转换
        return (List<E>)list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws SQLException, IntrospectionException, NoSuchFieldException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
        List<Object> objects=selectList(statementId,params);
        if(objects.size()==1){
            //如果查询结果只有一条，就直接返回
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果结果为空或结果不唯一");
        }

    }

    @Override
    public <T> T getMapper(Class<T> mapperClass) {
        //使用JDK动态代理为Dao接口生成代理实现类
        Object proxyInstance= Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] args) throws Throwable {
                //底层都还是去执行JDBC代码    //根据不同的情况，来调用selectList或者selectOne
                //准备参数 1：statmentid：sql语句的唯一表示：namespace，id=接口全限定名.方法名
                //方法名:findAll
                String methodName=method.getName();
                String className=method.getDeclaringClass().getName();
                String statementId=className+"."+methodName;//com.lagou.dao.UserDaoImpl.findAll
                //准备参数2：params
                //获取被调用方法的返回值类型
                Type genericReturnType=method.getGenericReturnType();
                //判断返回值类型是不是List,泛型类型参数化
                if(genericReturnType instanceof ParameterizedType){
                    List<Object> objects=selectList(statementId,args);
                    return objects;
                }

                return selectOne(statementId,args);
            }
        });


        return (T)proxyInstance;
    }
}
